package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public void addAddressBook(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.insertAddressBook(addressBook);
    }

    @Override
    public List<AddressBook> listByUserId() {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.listByUserId(userId);
        return list;
    }

    @Override
    public void setDefaultAddress(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.listByUserId(userId);
//        只能存在一个默认地址
        for (AddressBook addressBook : list) {
            if (addressBook.getIsDefault() == 1){
                addressBookMapper.cancelDefaultAddressById(addressBook.getId());
            }
        }
        addressBookMapper.setDefaultAddressById(id);
    }

    @Override
    public AddressBook queryDefaultAddress() {
//        直接全部查询再进行筛选
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.listByUserId(userId);
        for (AddressBook addressBook : list) {
            if (addressBook.getIsDefault() == 1){
                return addressBook;
            }
        }
//        addressBookMapper.queryDefaultAddressByUserIdAndIsDefault();
        return null;
    }

    @Override
    public AddressBook queryAddressById(Long id) {
        AddressBook addressBook = addressBookMapper.getAddressById(id);
        return addressBook;
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBookMapper.updateAddressBook(addressBook);
    }

    @Override
    public void deleteAddressBook(Long id) {
        addressBookMapper.deleteById(id);
    }
}
